package practice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: https://leetcode.cn/problems/3sum/
 * @Author Ammar
 * @Create 2023/7/19 19:40
 */
public class _15_三数之和 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> reslut = new ArrayList<>();
        Arrays.sort(nums);
        int lastIndex = nums.length - 3;
        int lastR = nums.length - 1;
        for (int i = 0; i <= lastIndex; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int l = i + 1; int r = lastR;
            while (l < r) {
                if (nums[l] + nums[r] + nums[i] == 0) {
                    reslut.add(Arrays.asList(nums[i], nums[l], nums[r]));
                    while (l < r && nums[l] == nums[l + 1]) l++;
                    while (l < r && nums[r] == nums[r - 1]) r--;
                    l++;
                    r--;
                } else if (nums[l] + nums[r] + nums[i] < 0) {
                    l++;
                } else {
                    r--;
                }
            }
        }
        return reslut;
    }
}
